<template>
  <!-- 导航栏 -->
  <van-nav-bar
    :title="title"
    fixed
    left-arrow
    @click-left="onClickLeft"
    @click-right="onClickRight"
  >
    <!-- 右侧按钮 -->
    <template #right>
      <van-icon name="setting-o" size="18" />
    </template>
  </van-nav-bar>

  <div id="content">
    <router-view />
  </div>

  <!-- <slot> 这里是内容 </slot> -->

  <!-- 标签页 -->
  <van-tabbar route>
    <van-tabbar-item to="/" icon="home-o" name="index">主页</van-tabbar-item>
    <van-tabbar-item to="/team" icon="paid" name="team">队伍 </van-tabbar-item>
    <van-tabbar-item to="/friend" icon="friends-o" name="friend"
      >联系人</van-tabbar-item
    >
    <van-tabbar-item to="/user" icon="user-o" name="user">个人</van-tabbar-item>
  </van-tabbar>
</template>

<!-- 脚本 -->
<script setup lang="ts">
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import { ref } from "vue";
import routes from "../config/route";
import { getCurrentUser } from "../service/user";

const router = useRouter();
// 默认页面标题
const DEFAULT_TITLE = "伙伴匹配";
// 页面标题
const title = ref(DEFAULT_TITLE);

// 校验是否登录, 未登录则跳转至登录页;
onMounted(async () => {
  const res = await getCurrentUser();
  console.log(res);
  if (!res.data) {
    console.log("未登录!");
    router.replace("/user/login");
  }
});

// 跳转页面前校验将要跳转的路由(目标路由)
router.beforeEach((to) => {
  // 拿取目标路由的path
  const toPath = to.path;
  // 逐个比对自定义路由中的path
  const route = routes.find((route) => {
    // 匹配到该路由的path
    return toPath == route.path;
  });
  // 设置title为匹配路由的title
  title.value = route?.title ?? DEFAULT_TITLE;
});

// 左”/“按钮, 返回上个页面
const onClickLeft = () => {
  router.back();
};
// 跳转至搜索页
const onClickRight = () => {
  router.push("/search");
};
</script>

<style></style>
